<?php

/**
 * 商品 历史数据 打标签
 * 需要打风格标签的商品范围：一级分类家具、家居日用、家居装饰、家电、灯饰建材下所有商品（不包含品牌以及门店商品）
 */

ini_set('display_errors', 1);
ini_set('memory_limit', -1); //不限制内存
ini_set("error_reporting", E_ALL);//显示所有错误

require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\service\wiki\AdmWikiTag;


$programStartTime = time();

//查询符合条件的商品

$where = [
    'basic_state[!]' => mWikiBasic::STATE_DEL,
    'category_id' => AdmWikiTag::CATEGORY_ID_ARR,
    'brand_id' => 0,
    'store_id' => 0,
    "ORDER" => ['id' => 'DESC'],
];
$maxWikiBasicId = mWikiBasic::get('id', $where);
$pageSize = 4000;

$page = ceil($maxWikiBasicId / $pageSize);
$styleList = AdmWikiTag::getStyleList();

$i = 0;
while ($i < $page) {
    $start = $i * $pageSize;
    $end = ($i + 1) * $pageSize;
    unset($where['ORDER']);
    $wikiBasicInfos = mWikiBasic::select(['id', 'style', 'title'], array_merge($where, ["id[<>]" => [$start, $end]]));
    $basicIds = array_column($wikiBasicInfos, 'id');
    $wikiInfos = mWiki::select(['tags', 'basic_id'], ['basic_id' => $basicIds, 'tags[!]' => '']);
    $wikiInfoMap = array_column($wikiInfos, 'tags', 'basic_id');
    upStyle($wikiBasicInfos, $styleList, $wikiInfoMap);
    $i++;
}
// 处理wiki是非官方商品并且品牌id>0的wiki_basic
$basicIdArr = mWiki::get('basic_id', [
    'status[!]' => mWiki::STATUS_DEL,
    'category_id' => AdmWikiTag::CATEGORY_ID_ARR,
    'is_official' => 0,//非官方商品
    'brand_id[>]' => 0,
    'store_id' => 0,
]);
if ($basicIdArr) {
    $wikiBasicInfos = mWikiBasic::select(['id', 'style', 'title'], ['id' => $basicIdArr]);
    $wikiInfos = mWiki::select(['tags', 'basic_id'], ['basic_id' => $basicIdArr, 'tags[!]' => '']);
    $wikiInfoMap = array_column($wikiInfos, 'tags', 'basic_id');
    upStyle($wikiBasicInfos, $styleList, $wikiInfoMap);
}
$programEndTime = time();
echo '共消耗时间'.($programEndTime - $programStartTime).PHP_EOL;

/**
 * @param $wikiBasicInfos
 * @param $styleList
 * @param $wikiInfoMap
 */
function upStyle($wikiBasicInfos, $styleList, $wikiInfoMap)
{
    if ($wikiBasicInfos) {
        $j = 0;
        foreach ($wikiBasicInfos as $item) {
            if (empty($item['style'])) {
                $tag = AdmWikiTag::matchWikiTags($styleList, $item['title']);
                if (isset($wikiInfoMap[$item['id']])) {
                    $wikiTags = AdmWikiTag::formatStyle($wikiInfoMap[$item['id']]);//第三方标签 参考
                    $tag = array_merge($tag, AdmWikiTag::matchWikiTags($styleList, $wikiTags));
                }
                if ($tag) {
                    mWikiBasic::updateData(['style' => implode(',', array_unique($tag))], ['id' => $item['id']]);
                    $j++;
                }
            }
        }
        echo '共修改'.$j.'条数据'.PHP_EOL;

    }
}